package com.example.springbootwebservice.interceptor;


import java.util.List;

import javax.xml.soap.SOAPException;

import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.springframework.util.StringUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    //默认登陆用户
    private String USERNAME="admin";
    //默认登陆用户密码
    private String PASSWORD="123456";

    public AuthInterceptor() {
        // 定义在什么阶段进行拦截
        super(Phase.PRE_PROTOCOL);
    }

    @Override
    public void handleMessage(SoapMessage soapMessage) throws Fault {
        String username = null;
        String password = null;
        List<Header> headers = soapMessage.getHeaders();
        if(headers == null) {
            throw new Fault(new IllegalArgumentException("headers未取到，无法验证用户信息"));
        }
        // 获取客户端传递的用户名和密码
        for (Header header : headers) {
            SoapHeader soapHeader = (SoapHeader) header;
            Element e = (Element) soapHeader.getObject();
            NodeList usernameNode = e.getElementsByTagName("username");
            NodeList passwordNode = e.getElementsByTagName("password");
            username = usernameNode.item(0).getTextContent();
            password = passwordNode.item(0).getTextContent();
            if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
                throw new Fault(new IllegalArgumentException("用户信息为空！"));
            }
        }
        // 校验客户端用户名密码是否和服务端一致
        if(!(username.equals(USERNAME) && password.equals(PASSWORD))) {
            throw new Fault(new SOAPException("用户信息认证失败！"));
        }
    }

}